import React, { Component } from 'react';
import { Tabs } from 'antd'
import { getTab } from '../../api'
import { List, Avatar, Space } from 'antd';
import { EyeOutlined, LikeOutlined, MessageOutlined } from '@ant-design/icons';
const { TabPane } = Tabs

class Index extends Component {
	state = {
		tabs: [],
		isActiveZan: false
	}
	async getTab() {
		const resp = await getTab()
		const { data } = resp.data
		this.setState({ tabs: data })
	}
	handleAddZan = (id) => {
		const { tabs } = this.state

		tabs.forEach(v => {
			const item = v.children.find(v => v.id === id)
			if(item) {
				item.isZan ? item.zan-- : item.zan++

				item.isZan = !item.isZan
			}
		})

		this.setState({ tabs: [...tabs] } )
	}
	handleAddReaded = (id) => {
		const { tabs } = this.state

		tabs.forEach(v => {
			const item = v.children.find(v => v.id === id)
			if(item) {
				item.readed++
			}
		})

		this.setState({ tabs: [...tabs] } )
	}
	componentDidMount() {
		this.state.tabs.length === 0 && this.getTab()
	}
	render() {
		const { tabs } = this.state
		return (
			<div>
				<Tabs>
					{
						tabs.length > 0 && tabs.map(v => {
							return (
								<TabPane tab={v.title} key={v.id}>
									<List
										itemLayout="vertical"
										size="large"
										dataSource={v.children}
										renderItem={v => (
											<List.Item
												key={v.title}
												extra={
													v.url ?
														<img
															width={100}
															alt="logo"
															src={v.url}
														/> : ''
												}
												onClick={ () => this.props.history.push({
													pathname: '/post/' + v.id,
													state: {
														...v,
														handleAddReaded: () => this.handleAddReaded(v.id)
													}
												}) }
											>
												<List.Item.Meta
													title={<>{v.nickname} | {v.title} | {v.datetime}</>}
													description={v.desc}
												/>
												<p>{v.content}</p>
												<div>
													<Space>

														<EyeOutlined 
															style={{
																fontSize: 20,
															}} 
															/>
														<span>{v.readed}</span>


														<LikeOutlined 
															style={{
																fontSize: 20,
																color:  v.isZan ? 'red' : ''
															}} 
															onClick={ () => this.handleAddZan(v.id) }
														/>
														<span>{v.zan}</span>


														<MessageOutlined style={{
															fontSize: 20,
														}} />
														<span>{v.mess.length}</span>

													</Space>
												</div>
											</List.Item>
										)}
									/>
								</TabPane>
							)
						})
					}
				</Tabs>
			</div>
		);
	}
}

export default Index;
